package com.project.system.user.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.project.common.constant.CommonConstant;
import com.project.common.util.JwtUtil;
import com.project.common.util.RedisUtil;
import com.project.common.util.Result;
import com.project.system.user.entity.AppLoginModel;
import com.project.system.user.entity.UserEntity;
import com.project.system.user.service.IUserService;
import com.project.system.user.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 员工登录
 *
 * @author yanhaizhen
 * @since 2022-02-28 13:37:44
 */
@Api(tags="登录")
@RestController
@RequestMapping("/user")
@Slf4j
public class LoginController {

    @Resource
    private IUserService userService;
    @Resource
    private RedisUtil redisUtil;

    @ApiOperation(value="用户登录", notes="登录")
    @PostMapping(value = "/login")
    public Result login(@RequestBody AppLoginModel appLoginModel){
        String phone = appLoginModel.getPhone();
        String password = appLoginModel.getPassword();
        log.info("用户登录:{},{}", phone, password);
        String passwordMd5 = SecureUtil.md5(password);

        if(StrUtil.isEmpty(phone)){
            return Result.error("手机号不能为空");
        }
        if(StrUtil.isEmpty(password)){
            return Result.error("密码不能为空");
        }

        // 根据手机号查询用户
        UserEntity user = userService.getUserByPhone(phone);
        if(user == null){
            return Result.error("用户不存在");
        }
        // 门店员工状态：0-禁用，1-启用
//        if(user.getStatus() == 0){
//            return Result.error("用户禁止登录");
//        }
        if(!passwordMd5.equals(user.getPassword())){
            return Result.error("密码错误");
        }

        // 返回数据  需要对接前端

        // 生成token
        String token = JwtUtil.sign(phone, passwordMd5);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);

        // 返回数据对象
        UserVO userVO = new UserVO();
        userVO.setToken(token);
        return Result.OK(userVO);
    }
}

